{% load navigation_tags %}
{% load event_tags %}
{% load static %}
{% block add_css %}
    <link rel="stylesheet" href="{% static "chosen-bootstrap/chosen.bootstrap.min.css" %}">
{% endblock %}
{% block css %}
    {{ form.media.css }}
{% endblock %}
{% block js %}    
    {{ form.media.js }}
{% endblock %}
<div class="filter-set">
    <form method="get" {% if form_id %}id="{{form_id}}"{% endif %} class="{{ request.path|slugify }}-filters form-inline dojo-filter-set">
        {% for field in form.hidden_fields %}
            {{ field }}
        {% endfor %}
        <div class="container-fluid filter-form-group">
                {% for field in form.visible_fields %}
                    <div class="col-lg-3 col-md-4 col-sm-6 col-12">
                        <div class="filter-form-input" style="min-width: 0;">
                            <label for="{{ field.auto_id }}" class="form-label mb-1" style="display: block;">
                                {{ field.label }}
                                {% if field.help_text %}
                                    <i class="fa-solid fa-circle-question has-popover" 
                                    data-trigger="hover" 
                                    data-content="{{ field.help_text }}" 
                                    data-placement="right" 
                                    data-container="body">
                                    </i>
                                {% endif %}
                            </label>
                            {% with placeholder="placeholder:"|add:field.label %}
                              {{ field|addcss:"class: form-control filter-form-control"|addcss:placeholder }}
                            {% endwith %}
                        </div>
                    </div>
                {% endfor %}
        </div>
        <div class="container-fluid">
            <div class="row mt-3">
            <div class="col-12">
                <div class="d-flex justify-content-end align-items-center">
                    {% if submit == 'report' %}
                        {% query_string_as_hidden %}
                        <button class="btn btn-secondary" name="_generate" type="submit">
                            <i class="fa-solid fa-file-lines"></i> Generate Report
                        </button>
                    {% else %}
                        <button id="apply" class="btn btn-secondary me-2">
                            <i class="fa-solid fa-filter"></i> Apply Filters
                        </button>
                        {% if clear_js %}
                            <a class="btn btn-outline-secondary me-2" href="#{{form_id}}" id="clear_js" role="button"> 
                                <i class="fa-solid fa-remove"></i> Clear Filters
                            </a>
                        {% else %}
                            <a class="btn btn-outline-secondary me-2" href="{{ clear_link|default:request.path }}" id="clear" role="button" >
                                <i class="fa-solid fa-remove"></i> Clear Filters
                            </a>
                        {% endif %}             
                        {% if restart_link %}
                            <a href="{{ restart_link }}" id="restart" class="btn btn-secondary">
                                <i class="fa-solid fa-remove"></i> Restart
                            </a>
                        {% endif %}
                        {% endif %}
                    </div>
                </div>
            </div>
        </div>
        
    </form>
</div>
<script>
    $(document).ready(function() {
    const form = $(".filter-set>form");
    $(form).first().submit(function(event) {
      var formData = $(".filter-set>form").first().serializeArray();
      var filteredFormData = formData.filter(function(item) {
        // Remove null or empty values
        return item.value !== "" && item.value !== null && item.value !== 'unknown';
      });
      // Construct the query parameters from the filtered data
      var queryParams = filteredFormData.map(function(item) {
        return encodeURIComponent(item.name) + "=" + encodeURIComponent(item.value);
      });

      // Get the current page's URL
      var currentPageURL = window.location.href;

      // Remove existing query parameters from the current URL
      var baseUrl = currentPageURL.split('?')[0];

      // Append the new query parameters to the base URL
      var newAction = baseUrl + "?" + queryParams.join("&");
      window.location.href = newAction;
      event.preventDefault();
    });

    // Clear filter logic below should clear filters without reload and 
    // have the button disabled if no filters are active

    const clearFilterLink = $("#clear, #clear_js");

    const hasActiveFilters = () => {
            return $(form)
                .find(":input:not([type='hidden'])")
                .filter(function () {
                    const value = $(this).val();

                    if ($(this).is("select[multiple]")) {
                        // Checking if value is an array and has non-empty elements at the same time
                        return Array.isArray(value) && value.some(v => v && v.trim() !== "");
                    } else if ($(this).is(":checkbox, :radio")) {
                        // Checkboxes and radio buttons
                        return $(this).prop("checked");
                    } else if (typeof value === "string") {
                        // Text inputs, textareas
                        return value.trim() !== "" && value !== "unknown" && value !== null;
                    } else {
                        // Other input types
                        return value !== null && value !== undefined;
                    }
                }).length > 0; 
        };

    const updateClearFiltersState = () => {
        const filtersActive = hasActiveFilters();

        if (clearFilterLink.length) {
            clearFilterLink
                .toggleClass("disabled", !filtersActive)
                .toggleClass("btn-outline-secondary", !filtersActive)
                .toggleClass("btn-secondary", filtersActive)
                .attr("aria-disabled", !filtersActive)
                .css("pointer-events", filtersActive ? "auto" : "none");
        }
    };

$(form).on("input change", updateClearFiltersState);

        $(document).on('click', '#clear, #clear_js', function (event) {
            event.preventDefault();
            if ($(this).attr("aria-disabled") === "true") {
                return;
            }
            const form = $(this).closest(".filter-set").find("form");
            if (form.length) {
                clear_form(form);
                // Refresh some UI components to work have cleared form from all respective libraries
                form.find("select.selectpicker").selectpicker("refresh");
                form.find(".multi-tag-input").val('').trigger('change');
                form.find("select.select2-hidden-accessible").val(null).trigger('change');
                form.find(".select2-selection__choice").remove();
                form.find(".select2-search__field").val('');
                // Update the state for the clear filters button
                updateClearFiltersState();

            }
        });
});
</script>
